﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
    

public partial class Registration2 : System.Web.UI.Page
{
   
    protected void Button1_Click(object sender, EventArgs e)
    {

        //Create ConnectionString Statement
        string connectionString = ConfigurationManager.ConnectionStrings["stockmarketConnectionString"].ConnectionString;

        //Create SQL connection
        SqlConnection con = new SqlConnection(connectionString);


        //Execute the sql command to database and verify enter user data.
        try
        {

            con.Open();
            SqlCommand cmd4 = new SqlCommand("select * from [User] where UserName='" + Usernametxt.Text.Trim() + "'", con);
            SqlCommand cmd5 = new SqlCommand("select EmailAddress from [User] where EmailAddress='" + emailtxt.Text.Trim() + "'", con);
            SqlDataReader dr = cmd4.ExecuteReader();
            lbl_msg1.Visible = false;
            lbl_msg2.Visible = false;
            lblMsg.Visible = false;
            lblmsg2.Visible = false;

            //Check if username is used.
            if (dr.HasRows)
            {
                lbl_msg1.Visible = true;
                lbl_msg1.ForeColor = System.Drawing.Color.Red;
                lbl_msg1.Text = "Username Not Available";
 
            }  
                
            else
            
            {
                dr.Close();
                dr = cmd5.ExecuteReader();


            //Check if email address is used.     

             if (dr.HasRows)
             {
                    lbl_msg2.Visible = true;
                    lbl_msg2.ForeColor = System.Drawing.Color.Red;
                    lbl_msg2.Text = "Email already used";
             }

             else
             {

            //Valid password requirements with the global settings.

                 bool validpasswordlength = PasswordRequirement.validpasswordlength(passwordtxt.Text.Trim());
                 int getpasswordlength = PasswordRequirement.getpasswordlength(passwordtxt.Text.Trim());

                 if (validpasswordlength == false)


                    {
                        lblmsg2.Visible = true;
                        lblmsg2.Text = "Password length needs to be " + getpasswordlength + "" ;
                    
                    
                    }

      
                  else
                    {
                        bool validuppercase = PasswordRequirement.validuppercase(passwordtxt.Text.Trim());
                        int getuppercase = PasswordRequirement.getupperchar(passwordtxt.Text.Trim());

                        if (validuppercase == false)
                        {
                            lblmsg2.Visible = true;
                            lblmsg2.Text = "Password needs to contain " + getuppercase + " uppercase characters.";

                        }

                  else
                    {

                        bool validlowercase = PasswordRequirement.validlowercase(passwordtxt.Text.Trim());
                        int getlowercase = PasswordRequirement.getlowerchar(passwordtxt.Text.Trim());

                        if (validlowercase == false)
                        {
                            lblmsg2.Visible = true;
                            lblmsg2.Text = "Password needs to contain " + getlowercase + " lowercase characters.";

                        }
                  else

                    {
                            bool validspecialchar = PasswordRequirement.validspecialchar(passwordtxt.Text.Trim());
                            int getspecialchar = PasswordRequirement.getspecialchar(passwordtxt.Text.Trim());

                            if (validspecialchar == false)
                            {
                                lblmsg2.Visible = true;
                                lblmsg2.Text = "Password needs to contain " + getspecialchar + " special characters.";

                            }

                  else

                   {

                        //Register user data into user table and password history table.

                        dr.Close();
                        string insertSql = "INSERT INTO [User] (UserName,FirstName,lastname,hash,hash2,emailaddress,contact,nationality,occupation,company,AccountAmount) values (@UserName,@FirstName,@LastName,@hash,@hash2,@emailaddress,@contact,@nationality,@occupation,@company,@accountamount)";
                        string insertSql2 = "INSERT INTO [PasswordHistory] (UserName,changeDate,hash,hash2) values (@UserName,@changeDate,@hash,@hash2)";
                        string insertSql3 = @"UPDATE
                                            [User]
                                            SET
                                            AccountAmount = (AccountAmount + (SELECT ReferalAmount FROM GlobalSetting))
                                            WHERE
                                            ReferalCode = @ReferalCode
                                            ";
                        String getSql3 = "Select Initialamount from [GlobalSetting]";

                        //Create SQL Command And Sql Parameters

                        SqlCommand cmd = new SqlCommand(insertSql, con);
                        SqlCommand cmd2 = new SqlCommand(insertSql2, con);
                        SqlCommand cmd3 = new SqlCommand(getSql3, con);
                        SqlCommand cmd6 = new SqlCommand(insertSql3, con);
                               
                        String intialamount = cmd3.ExecuteScalar().ToString();
                        int amt = Convert.ToInt32(intialamount);
                                
                        //User table fields.
                        SqlParameter UserName = new SqlParameter("@UserName", SqlDbType.VarChar, 15);
                        UserName.Value = Usernametxt.Text.Trim().ToString();
                        cmd.Parameters.Add(UserName);

                        SqlParameter firstname = new SqlParameter("@FirstName", SqlDbType.NVarChar, 50);
                        firstname.Value = firstnametxt.Text.Trim().ToString();
                        cmd.Parameters.Add(firstname);

                        SqlParameter lastname = new SqlParameter("@lastname", SqlDbType.NVarChar, 50);
                        lastname.Value = lastnametxt.Text.Trim().ToString();
                        cmd.Parameters.Add(lastname);

                        //Encrypt password field
                                
                        SqlParameter hash = new SqlParameter("@hash", SqlDbType.VarChar);
                        passwordtxt.Text = SSTCryptographer.Encrypt(passwordtxt.Text.Trim(), "SampleKey");
                        hash.Value = passwordtxt.Text.Trim().ToString();
                        cmd.Parameters.Add(hash);

                        SqlParameter hash2 = new SqlParameter("@hash2", SqlDbType.VarChar);
                        confirmpwdtxt.Text = SSTCryptographer.Encrypt(confirmpwdtxt.Text.Trim(), "SampleKey");
                        hash2.Value = confirmpwdtxt.Text.Trim().ToString();
                        cmd.Parameters.Add(hash2);

                        SqlParameter emailaddress = new SqlParameter("@emailaddress", SqlDbType.VarChar, 50);
                        emailaddress.Value = emailtxt.Text.Trim().ToString();
                        cmd.Parameters.Add(emailaddress);

                        SqlParameter contact = new SqlParameter("@contact", SqlDbType.NChar, 8);
                        contact.Value = contacttxt.Text.Trim().ToString();
                        cmd.Parameters.Add(contact);

                        SqlParameter nationality = new SqlParameter("@nationality", SqlDbType.VarChar, 50);
                        nationality.Value = Countrytxt.Text.Trim().ToString();
                        cmd.Parameters.Add(nationality);

                        SqlParameter occupation = new SqlParameter("@occupation", SqlDbType.VarChar, 30);
                        occupation.Value = Occupationtxt.Text.Trim().ToString();
                        cmd.Parameters.Add(occupation);

                        SqlParameter company = new SqlParameter("@company", SqlDbType.VarChar, 80);
                        company.Value = companytxt.Text.Trim().ToString();
                        cmd.Parameters.Add(company);

                        SqlParameter accountamount = new SqlParameter("@accountamount", SqlDbType.Int);
                        accountamount.Value = amt;
                        cmd.Parameters.Add(accountamount);


                        //Password history table field.
                        SqlParameter UserName2 = new SqlParameter("@UserName", SqlDbType.VarChar, 15);
                        UserName2.Value = Usernametxt.Text.Trim().ToString();
                        cmd2.Parameters.Add(UserName2);

                        SqlParameter changedate2 = new SqlParameter("@changeDate", SqlDbType.DateTime);
                        changedate2.Value = System.DateTime.Now;
                        cmd2.Parameters.Add(changedate2);
                       
                        SqlParameter hashno1 = new SqlParameter("@hash", SqlDbType.VarChar);
                        hashno1.Value = passwordtxt.Text.Trim().ToString();
                        cmd2.Parameters.Add(hashno1);

                        SqlParameter hashno2 = new SqlParameter("@hash2", SqlDbType.VarChar);
                        hashno2.Value = confirmpwdtxt.Text.Trim().ToString();
                        cmd2.Parameters.Add(hashno2);

                      
                        cmd6.Parameters.AddWithValue("ReferalCode", ReferalCodeBox.Text);
                        
                        //Execute Sqlcommands and display sucess message.
                        cmd.ExecuteNonQuery();
                        cmd2.ExecuteNonQuery();
                        cmd6.ExecuteNonQuery();
                        lbl_msg1.Visible = false;
                        lbl_msg2.Visible = false;
                        lblmsg2.Visible = false;
                        lblMsg.Visible = true;
                        lblMsg.Text = "User Registration successful";

                        Response.Write("<script language='javascript'>alert('User Account Register Successful.');window.location.href='Login.aspx'</script>");             
                        
                        //Reset controls values in the page.
                        ResetFormControlValues(this);
                              
                            
                            
                         }

                     }

  
                  }
   
                    
              }

 
          }
            
            
     }


 }


        catch (SqlException ex)
        {
            string errorMessage = "Error in Registering user";
            errorMessage += ex.Message;
            throw new Exception(errorMessage);

        }

        finally
        {
            con.Close();
        }


    }


    

    private void ResetFormControlValues(Control parent)
    {
        foreach (Control c in parent.Controls)
        {
            if (c.Controls.Count > 0)
            {
                ResetFormControlValues(c);
            }
            else
            {
                switch (c.GetType().ToString())
                {
                    case "System.Web.UI.WebControls.TextBox":
                        ((TextBox)c).Text = "";
                        break;
                    case "System.Web.UI.WebControls.CheckBox":
                        ((CheckBox)c).Checked = false;
                        break;
                    case "System.Web.UI.WebControls.RadioButton":
                        ((RadioButton)c).Checked = false;
                        break;

                }
            }
        }
    }


    
}